package config

import (
	"flag"
	"fmt"
	"os"
	"path/filepath"

	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

func init() {
	defaultConfig()
	initCommandLines()
	parseConfig()
}

var configPath string

func initCommandLines() {
	flag.StringVar(&configPath, "config", "../../configs/app.json", "config file")
	flag.Parse()
}

func defaultConfig() {
	viper.SetDefault("server.port", 8977)
	viper.SetDefault("server.name", "message")
	viper.SetDefault("logger.path", "./logs/")
	viper.SetDefault("logger.name", "message")
	viper.SetDefault("logger.level", "debug")
	viper.SetDefault("logger.console", true)
}

func parseConfig() {
	viper.SetConfigFile(configPath)
	viper.SetConfigType("json")
	err := viper.ReadInConfig()
	if err != nil {
		fmt.Printf("use default config, because config read failed,err:%s", err.Error())
	}
	viper.WatchConfig()

	viper.OnConfigChange(func(in fsnotify.Event) {
		fmt.Println("配置文件修改了...")
		fmt.Println(in.Name, in.Op)
	})
}

func getServiceName() string {
	servicePath := os.Args[0]
	fmt.Println(servicePath)
	_, fileName := filepath.Split(servicePath)
	return fileName
}

func GetServerName() string {
	name := viper.GetString("server.name")
	if name == "" {
		return flag.Arg(0)
	}
	return name
}

func GetServerAddr() string {
	port := viper.GetString("server.port")
	return ":" + port
}

func GetLoggerLevel() string {
	return viper.GetString("logger.level")
}

func GetLoggerPath() string {
	return viper.GetString("logger.path")
}

func GetLoggerName() string {
	return viper.GetString("logger.name")
}

func IsOutConsole() bool {
	return viper.GetBool("logger.console")
}

func GetDbHost() string {
	return viper.GetString("db.host")
}

func GetDbPort() int32 {
	return viper.GetInt32("db.port")
}

func GetDbDatabase() string {
	return viper.GetString("db.database")
}

func GetDbUserName() string {
	return viper.GetString("db.userName")
}

func GetDbPassword() string {
	return viper.GetString("db.password")
}
